package server.mapper;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.DealWebxml;
import server.HttpServlet;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapperWrapper<String,Object> extends HashMap {

    /**
     * 加载解析web.xml,初始化servlet
     */
    public Map loadServlet()  {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");

            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);

                //<servlet-name>lagou</servlet-name>
                //Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                List<Element>  servletNameElements = element.selectNodes("servlet-name");
                for(int j=0;j<servletNameElements.size();j++){
                    Element element1 = selectNodes.get(j);
                    java.lang.String servletName = servletNameElements.get(j).getStringValue(); //<servlet-class>server.LagouServlet</servlet-class>
                    Element servleClassElement = (Element) element.selectSingleNode("servlet-class");
                    java.lang.String servletClass = servleClassElement.getStringValue();

                    //根据servlet-name的值找到url-pattern>
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    //  /lagou
                    java.lang.String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                    //lagouServlet  /lagou
                    this.put((HttpServlet) Class.forName(servletClass).newInstance(),urlPattern);
                }

                //servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }


}
